#!/usr/bin/env python

# copyright 2010 Studio Cypher, LLC
# developer: Will Emigh
# projects@studiocypher.com

# Custom modules
from authentication import user_required
from authentication import get_account_from_user
from models import Account
from models import Planet
from models import Colony
from models import ProfilerRecord
from models import TradeRecord
from models import MessageRecord
from models import Log

# Built-in or Google modules
import cgi
import os
#import imghdr
from google.appengine.ext.webapp import template
from google.appengine.api import images
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db

class LinkedListNode():
    def __init__ (self):
        self.prev = None
        self.next = None
        self.object = None
        self.value = 0
    
    # insert a new object into the list in a descending order by object.value
    def insertDesc (self, object, value):
        inserted = False
        thisNode = LinkedListNode()  #self
        thisNode.prev = self.prev
        thisNode.next = self.next
        thisNode.value = self.value
        thisNode.object = self.object
        
        while (thisNode):
            if (value >= thisNode.value):
                # insert new node in front of thisNode
                newNode = LinkedListNode()
                newNode.value = value
                newNode.object = object
                newNode.prev = thisNode.prev
                thisNode.prev = newNode
                newNode.next = thisNode
                inserted = True
                break
            thisNode = thisNode.next
        if (not inserted):
            # we arrived at the end of the list, so insert there
            newNode = LinkedListNode()
            newNode.value = value
            newNode.object = object
            newNode.next = None
            newNode.prev = thisNode
            thisNode.next = newNode
            
    def dump(self):
        # traverse list building up array
        retAr = []
        thisNode = self
        while (thisNode != None):
            retAr.append(thisNode.object)
            thisNode = thisNode.next
        return retAr
            



class ChangeProfile(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
        newimage = str(self.request.get("newimage"))
        if( newimage ):
            account.image = db.Blob(newimage)
        about = self.request.get("about")
        if( about ):
            account.about = about
        account.put()
        self.redirect('/profiler/private?res_type=5')
           


class UpdateProfile(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
            
        if account:                        

				
            template_values = {
            'account': account,
            }

            path = os.path.join(os.path.dirname(__file__), 'update.html')
            self.response.out.write(template.render(path, template_values))
        
        else:
            self.redirect("/admin/login");
            
            

class PublicProfilePage(webapp.RequestHandler):
    def get(self):
        accountKey = self.request.get("account_key")
        account = Account.get(db.Key(accountKey))
        #account = db.get(db.Key(encoded=self.request.get("account_key")))
            
        if account:        
            for this_colony in account.colonies:
                planet = Planet.get(this_colony)
                all_colonies = Colony.all()
                colony = all_colonies.filter("owner =", account.key()).filter("location =", planet.key())
                

				
            template_values = {
            'account': account,
            }

            path = os.path.join(os.path.dirname(__file__), 'public_profile.html')
            self.response.out.write(template.render(path, template_values))
        
        else:
            self.redirect("/admin/login");
            
            
 
class PrivateProfilePage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        account = get_account_from_user(user)
            
        profilerArr = []
        logs = []
        if account:        
            for this_colony in account.colonies:
                planet = Planet.get(this_colony)
                all_colonies = Colony.all()
                colony = all_colonies.filter("owner =", account.key()).filter("location =", planet.key())
                profilerRec = ProfilerRecord()
                profilerRec.planet = planet
                profilerRec.colony = colony[0]
                profilerRec.distance = planet.get_distance(account.current_planet)
                profilerRec.put()
                profilerArr.append(profilerRec)
                
            resType = int(self.request.get("res_type"))
            if (not resType ):
                resType = 1

            if (resType == 1) :
                # bubble sort into descending order by resourceOne
                for up in range(0, len(profilerArr)-1):
                    down = up
                    while (down >= 0):
                        if ( profilerArr[down].colony.resourceStorage.resourceOne < profilerArr[down+1].colony.resourceStorage.resourceOne ):
                            # swap the two elements
                            tmp = profilerArr[down]
                            profilerArr[down] = profilerArr[down+1]
                            profilerArr[down+1] = tmp
                        down -= 1


            elif (resType == 2) :
                # bubble sort into descending order by resourceOne
                for up in range(0, len(profilerArr)-1):
                    down = up
                    while (down >= 0):
                        if ( profilerArr[down].colony.resourceStorage.resourceTwo < profilerArr[down+1].colony.resourceStorage.resourceTwo ):
                            # swap the two elements
                            tmp = profilerArr[down]
                            profilerArr[down] = profilerArr[down+1]
                            profilerArr[down+1] = tmp
                        down -= 1


            elif (resType == 3) :
                # bubble sort into descending order by resourceOne
                for up in range(0, len(profilerArr)-1):
                    down = up
                    while (down >= 0):
                        if ( profilerArr[down].colony.resourceStorage.resourceThree < profilerArr[down+1].colony.resourceStorage.resourceThree ):
                            # swap the two elements
                            tmp = profilerArr[down]
                            profilerArr[down] = profilerArr[down+1]
                            profilerArr[down+1] = tmp
                        down -= 1


            elif (resType == 4) :
                # bubble sort into descending order by resourceOne
                for up in range(0, len(profilerArr)-1):
                    down = up
                    while (down >= 0):
                        if ( profilerArr[down].colony.resourceStorage.resourceFour < profilerArr[down+1].colony.resourceStorage.resourceFour ):
                            # swap the two elements
                            tmp = profilerArr[down]
                            profilerArr[down] = profilerArr[down+1]
                            profilerArr[down+1] = tmp
                        down -= 1

            elif (resType == 5) :
                # bubble sort into descending order by resourceOne
                for up in range(0, len(profilerArr)-1):
                    down = up
                    while (down >= 0):
                        if ( profilerArr[down].distance > profilerArr[down+1].distance ):
                            # swap the two elements
                            tmp = profilerArr[down]
                            profilerArr[down] = profilerArr[down+1]
                            profilerArr[down+1] = tmp
                        down -= 1
            
            all_offers = TradeRecord.all()
            offers = all_offers.filter('to =', str(account.key()))
            all_messages = MessageRecord.all()
            messages = all_messages.filter('to =', str(account.key()))
             
            template_values = {
            'account': account,
            'profilerArr': profilerArr,
            'offers': offers,
            'messages': messages,
            }

            path = os.path.join(os.path.dirname(__file__), 'private_profile.html')
            self.response.out.write(template.render(path, template_values))
        
        else:
            self.redirect("/admin/login");
            
            
            

class GetImage(webapp.RequestHandler):
    def get(self):
        accountKey = self.request.get("account_key")
        account = Account.get(db.Key(accountKey))
        #image = image.Image(account.image)
        self.response.headers['Content-Type'] = 'image/png'
        self.response.out.write(account.image)
        

application = webapp.WSGIApplication(
                                     [('/profiler/public', PublicProfilePage),
                                      ('/profiler/private', PrivateProfilePage),
                                      ('/profiler/update', UpdateProfile),
                                      ('/profiler/change', ChangeProfile),
                                      ('/profiler/getimage', GetImage),],
                                     debug=True)									 
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
